#!usr/bin/python
# encoding=utf-8
import re
import random
import string
import time
import urllib
from multiprocessing.pool import ThreadPool
import sys
class Utils:
    def filterTitle(title1,str):
        string = re.sub(r'[\u4e00-\u9fa5]', '', str)
        return title1+string
    def filterStr(str):
        try:
            string = re.sub(r'\\ufffd', ' ', str)
        except:  
            return str
            
      
        return string
    def randomString(self,num=10):
        ranStr = ''.join(random.sample(string.ascii_letters + string.digits,num))
        return ranStr
    def formatSize(size):
        byteArr = re.findall(r'(\d*\.\d+)|(\d*)',size)[0]
        if byteArr[1]=='':
            byte=byteArr[0]
        else:
            byte = byteArr[1]
        # print(byte[1])
        unit = re.findall(r'MB|GB|KB|BYTES|mb|Mb|Gb|gb|Kb|kb|Bytes|bytes|g|m|k|b|G|M|K|B',size)[0]
        # byte = arr[1]
        # unit = arr[2].strip()
        data =  {'MB': 1024 * 1024, 'GB': 1024 * 1024 * 1024, 'KB': 1024, 'BYTES': 1, 'G': 1024 * 1024 * 1024,'M': 1024 * 1024, 'K': 1024,'B':1}
        # print(byte[unit[1].upper()])
        # print(byte)
        # print(unit)
        return int(float(byte) * data[unit.upper()])
    def formatSizeStr(time):
        time = re.sub(r'[^0-9a-zA-z ]','-',time)
        time =  re.split('-*',time)

        return time[len(time) - 2].strip()

    def formatMagnet(manet):
        magnet2 = re.findall(r'xt=urn:btih:\w*',manet)
        return magnet2[0].split(':')[2]

    def verify_datetime(datetime_):
        pattern = r'((?!0000)[0-9]{4}-((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31)|([0-9]{2}(0[48]|[2468][048]|[13579][26])|(0[48]|[2468][048]|[13579][26])00)-02-29) (20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$'
        if re.match(pattern, datetime_):
            return True

    def url_response(url):

        path, url = url
        # print(url)
        urllib.request.urlretrieve(url,path)
    @classmethod
    def format_date_tz(self, raw_date):
        date = raw_date.replace('T', ' ').replace('Z', '').split('+')[0]
        if not self.verify_datetime(date):
            raise ValueError(raw_date, date)
        return date

    @classmethod
    def get_random_time(self):
        H = str(random.randint(0, 23))
        M = str(random.randint(0, 59))
        S = str(random.randint(0, 59))
        random_time = [H, M, S]
        for i in range(0, len(random_time)):
            if len(random_time[i]) == 1:
                random_time[i] = '0' + random_time[i]
        time_ = ':'.join(random_time)
        return time_

    @classmethod
    def get_curr_time(self):
        # print(11111111111)
        time_ = time.strftime('%H:%M:%S', time.localtime(time.time()))
        # print(time_)
        return time_

    def formatTitle(title):
        title = re.sub(r'[^\u4e00-\u9fa5a-zA-z0-9.：:\s-]|.torrent|[\u200e]','',title)
        return title
    def getKeyWords(title):
        title = re.sub(r'[^\u4e00-\u9fa5a-zA-z0-9.\s-]|[字幕社]|[MP4字幕社招人內詳]|[字幕组]|[外挂]|[工作室]|[字幕組]|[字幕組]|[字幕]|[字幕社]|[新番]|torrent|rar|rmvb|[\[]|[\]]|[.]|1080|[喵萌奶茶屋]]',' ',title)

        if title == '':
            return ''

        title = title.split(' ')
        # print(title)
        titleArr = []
        if len(title)<1:
            return ''

        for key,item in enumerate(title):
            # print(item)
            if len(item)>4:
                titleArr.append(item)

        # print(1111)
        # print(titleArr)
        words = ','.join(titleArr)
        # print(words)
        if words == None:
            words = ''
        return words
    def formatTimeStr(time):
        time = re.sub(r'[^0-9\-]','',time)
        return time
    def formatTimeStr1(time):
        time = re.findall(r'[0-9]{4}\年[0-9]{2}\月[0-9]{2}',time)
        return time[0].replace('年','-').replace('月','-')
    @classmethod
    def formatTime(self,time):
        # 转换成时间数组
        try:
            timeData = time.split(' ')

            fit = re.findall(r'[/]|[-]', timeData[0])
            # print('------------------')

            checkTime = timeData[0].split(fit[0])
            # print(checkTime)
            # if int(checkTime[0])==2021:
            #     return time

            month = int(checkTime[1])
            # month = 2
            # print(month)
            if month==2 and int(checkTime[2])>29:
                checkTime[2] = 22

            if month<10:
                month = '0%d' % (month)
               

            day    = int(checkTime[2])
            
            if day>31:
                day = int(random.randint(1,27))
            if day<10:
                day = '0%d' % (day)        
            time1 = '%s-%s-%s' %(checkTime[0],month,day)

            # time2 = '%s:%s:%s' %(checkTime1[0],checkTime1[1],checkTime1[2])
            # time2 = self.get_random_time()
            # print(2222222222)
            time2 = self.get_curr_time()

            return '%s %s' %(time1,time2)
        except:
            return '2020-04-08 18:20:39'

    @classmethod
    def formatDownUrl(self,urls):
        # print(urls)
        urls = re.sub(r'dialog', 'download', urls)
        urls = re.sub(r'-ajax-1', '', urls)
        return urls